# This file is part of ModularBot.
# Copyright (C) 2005 Pierre Ducroquet (pierre.linux59@wanadoo.fr)

# ModularBot is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# ModularBot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with ModularBot; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import md5
from pysqlite2 import dbapi2 as sqlite

#CREATE TABLE rights ( userid INTEGER, right TEXT);
#CREATE TABLE users ( idx INTEGER PRIMARY KEY, username TEXT, admin BOOLEAN, core_admin BOOLEAN, password TEXT);

class RightsPlugin:
	def __init__ (self, filename):
		self.filename = filename
		self.queries = {"has_right": "SELECT * FROM rights r, users u WHERE r.userid = u.idx AND u.username = :name AND r.right = :right", \
						"admin": "SELECT admin FROM users u WHERE u.username = :name", \
						"core_admin": "SELECT core_admin FROM users u WHERE u.username = :name", \
						"password": "SELECT password FROM users u WHERE u.username = :name"}
	
	def parse (self):
		self.connec = sqlite.connect(self.filename)
		self.cursor = self.connec.cursor()
	
	def close (self):
		self.cursor.close()
		self.connec.close()
		
	def has_right (self, user, right):
		self.cursor.execute(self.queries["has_right"], {"name": user, "right": right})
		if len(self.cursor.fetchall()) == 0:
			return False
		else:
			return True
	
	def is_core_admin (self, user):
		self.cursor.execute(self.queries["core_admin"], {"name": user})
		if self.cursor.fetchall()[0][0] == "true":
			return True
		else:
			return False

	def is_admin (self, user):
		self.cursor.execute(self.queries["admin"], {"name": user})
		if self.cursor.fetchall()[0][0] == "true":
			return True
		else:
			return False
	
	def check_passwd (self, user, passwd):
		passmd5 = md5.new(passwd.strip())
		print user
		self.cursor.execute(self.queries["password"], {"name": user})
		if self.cursor.fetchall()[0][0] == passmd5.hexdigest():
			return True
		return False